var paginationTotal = 20;//记录总数
var isSearch = false;
var browseType = 'fold';    //浏览<{$lang.type}>
var isReload=false;
function search(val){
	if(val != undefined){
		$('#shipping_method_sch').val(val);
	}
	isSearch = true;
	paginationCurrentPage=1;
	initData(0);
}


function shiptype_search(val,obj){
	//$(".shiptype a").removeClass('sel');	
	//$(obj).addClass('sel');
	search(val);
}


function loadData(page, pageSize) {
    var vForm = {};
    if (isSearch == true && isSearch != undefined) {
        vForm = $("#sForm").serialize();
        vForm+='&browsetype='+browseType;
    }
    vForm.browsetype = browseType;
    loading();
    $.ajax({
        type: "POST",
        async: false,
        dataType: "json",
        url: "/order/order/list/page/" + page + "/pageSize/" + pageSize,
        data: vForm,
        success: function(json) {
            closeLoading();
            var list = "";
            var trclass="";
            paginationTotal = json.count;
			var i = (page == 1 ? 1 : pageSize * (page - 1) + 1);
            if (json.ask == 0) {
                list = "<td colspan='13' class=\"center\">&nbsp;<{$lang.no_data}></td>";
            } else {
                //var i = page==1 ? 1 : pageSize * (page-1)+1;
                $.each(json.result, function(key, val) {
                    if ((key + 1) % 2 == 1 ) {
                        trclass='';
                    } else {
                        trclass='even-tr';
                    }
                    if(browseType!='fold'){trclass='';}
                    list += "<tr class="+trclass+">";
                    list += "<td><input type='checkbox' value='" + val.orders_code + "' id='orderids_" + val.orders_code + "' name='orderids[]'></td>";
					list += '<td>'+(key+1)+'</td>';
                    list += "<td  style='text-align:left'><{$lang.orders_code}>：<a href=\"javascript:detail('" + val.orders_code + "')\">" + val.orders_code + "</a>";
                    list += "<br/><{$lang.trackNo}>：" + val.tracking_number + "";
                    list += "<br/><{$lang.op_code}>：" + val.op_code + "</td>";
                    list += "<td>" + val.customer_order_code + "</td>";
                    list += "<td>" + val.customer_id + "</td>";
                    list += "<td>" + val.consignee_country_id + "</td>";
                    list += "<td>" + val.shipping_method + "</td>";
                    list += "<td>" + val.sum<{$lang.sku}> + "</td>";
                    list += "<td style='text-align:left'><{$lang.create_time}>:" + val.add_time + "";
                    list += "<br/><{$lang.print_time}>:" + val.print_time + "";
                    list += "<br/><{$lang.ship_time}>:" + val.ship_date + "</td>";
					
					var packer= (val.packer==null) ? '<{$lang.null}>' : val.packer;
					var shipmenter=(val.shipmenter==null)?'<{$lang.null}>':val.shipmenter;
					
					list += "<td style='text-align:left;width:78px;'><{$lang.package_user}>:" + packer +"";
                    list += "<br/><{$lang.pickup_user}>:" + val.pickup_user +"";
                    list += "<br/><{$lang.ship_user}>:" + shipmenter + "</td>";
					
                    //list += "<td>" + val.pickup_user + "</td>";
					
					
                    list += "<td>" + val.orders_status_ch+"/"+val.process_status_ch + "</td>";
                    list += "<td>" ;
                    if(val.process_status<5&&val.process_status>0){
                    	list += "<a href='javascript:;' onclick='del("+val.order_id+",\""+val.orders_code+"\","+val.process_status+");'>" +
                    	"<img src='/images/icon/delete.gif' title='<{$lang.delete}>'></a>" ;
                    }
                    /*if(val.orders_status>2){
                        list += "&nbsp;<a href='javascript:;' onclick='problem(\""+val.orders_code+"\");'>" +	"<img src='/images/icon/edit.gif' title='问题件'></a>" ;
                    }
                    */
                    list += "</td>";
                    list += "</tr>";
                    if (val.order_product != null && val.order_product !='') {
                        list += "<tr><td colspan='13' style='padding:0;'>";
                        $.each(val.order_product, function(key, value) {
                            list += "<table width=100% border=0 cellspacing=0 cellpadding=0><tr class='even-tr'>";
                            list+="<td width='8%'>&nbsp;</td>";
//                            list += "<td width='20%'><{$lang.sku}>:<a href=\"javascript:proDetails('" + value.op_id + "')\">" + val.customer_id+"-"+value.product_sku + "</a></td>";
                            list += "<td width='20%'><{$lang.sku}>:" + val.customer_id+"-"+value.product_sku + "</td>";
                             list += "<td width='10%'><{$lang.quantity}>:" + value.op_quantity + "</td>";
                            list += "<td width='20%'><{$lang.category}>:" + value.category + "</td>";
                            list += "<td><{$lang.ws_code}>:" + value.ws_code + "</td>";
                            list += "</tr></table>";
                        });
                        list += "</td></tr>";
                    }
                });
            }
            $("#loadData").html(list);
        }
    });
}
function down(obj){
	var orders_codes = [];
	if($("[name='orderids[]']:checked").size()<1){
		alertTip("<{$lang.select_order}>");
		return false;
	}
	$("[name='orderids[]']:checked").each(function(i){
		orders_codes[i] = $(this).val();		
	});
	for(var a in orders_codes){
		//alert(orders_codes[a]);
	}
	$("#downloadForm_submit").click();
//	var params = {orders_codes:orders_codes};
//	loading();
//    $.ajax({
//        type: "POST",
//        async: false,
//        dataType: "html",
//        url: "/order/order/down/",
//        data: params,
//        success: function(html) {
//            closeLoading();
//            var pwin = window.open ('down.html','newwindow','height=100,width=400,top=0,left=0,toolbar=no,menubar=no,scrollbars=no, resizable=no,location=no, status=no') 
//            pwin.document.write(html);   
//            pwin.document.close();
//        }
//    });
}
$(function() {

    $.timepicker.regional['ru'] = {
		timeText: '<{$lang.pls}><{$lang.time}>',
		hourText: '<{$lang.hour}>',
		minuteText: '<{$lang.minite}>',
		secondText: '<{$lang.second}>',
		millisecText: '<{$lang.millisecond}>',
		currentText: '<{$lang.current}><{$lang.time}>',
		closeText: '<{$lang.ok}>',
		ampm: false
	};
	$.timepicker.setDefaults($.timepicker.regional['ru']);

	<{if $lang.current_language=='cn'}>
	var dayNamesMin =['日','一', '二', '三', '四', '五', '六'];
    var monthNamesShort = ['01月','02月','03月','04月','05月','06月','07月','08月','09月','10月','11月','12月'];
    $('#dateFrom,#dateTo').datetimepicker({
        dayNamesMin:dayNamesMin,
        monthNamesShort:monthNamesShort,
        changeMonth:true,
        changeYear:true,
        dateFormat:'yy-mm-dd'       
    });
	<{else}>
	 $('#dateFrom,#dateTo').datetimepicker({
	        changeMonth:true,
	        changeYear:true,
	        dateFormat:'yy-mm-dd'       
	    });
	<{/if}>
//    initData(0);
    
    $("[name=ckAll]").click(function() {
        if ($(this).is(':checked')) {
            $("[name='orderids[]']").attr('checked', true);
        } else {
            $("[name='orderids[]']").attr('checked', false);
        }
    });

    $('#order_form').dialog({
        autoOpen: false,
        width: 800,
        modal: true,
        show:"slide",
        buttons: {
            '<{$lang.ok}>': function() {
                submitOrder();
            },
            '<{$lang.cancel}>': function() {
                $(this).dialog('close');
            }
        },
        close: function() {
            $('#orderForm')[0].reset();
        }
    });
    // <{$lang.delete}>
	$("#right_confirm").dialog({
		autoOpen : false,
		modal : true,
		height : 'auto',
		show : "slide",
		buttons : {
			'<{$lang.ok}>' : function() {
				$('#message').text("");
				loading();
				$.ajax({ // 这里使用到Jquery的ajax<{$lang.method}>
					type : "POST",
					async : false,
					dataType : "json",
					url : "/order/order/delete", // 请求的处理url
					data : {
						'order_code' : Uorder_code
					},
					success : function(json) {
						closeLoading();
						if (json.ask == 1) {// <{$lang.operation}><{$lang.success}>
							$('#alert_msg p').html("<{$lang.operation}><{$lang.success}>");
							$('#alert_msg').dialog('open');
							loadData(paginationCurrentPage, paginationPageSize);
						} else {
							$('#alert_msg p').text("<{$lang.operation}><{$lang.fail}>  :"+json.msg);
							$('#alert_msg').dialog('open');
						}
					}
				});
				$(this).dialog('close');
			},
			'<{$lang.cancel}>' : function() {
				$(this).dialog('close');
			}
		}
	});
	
	// 弹出<{$lang.tip}>
	$("#alert_msg").dialog({
		autoOpen : false,
		modal : true,
		width : 400,
		show : "slide",
		buttons : {
			'<{$lang.close}>' : function() {
				$(this).dialog('close');
			}
		}

	});
	//回车处理
	$("#code").add("#customerId").keyup(function(e){
		var key = e.which;
		if(key==13){
			search();
		}
	});

    $("#comment-dialog").dialog({
        autoOpen:false,
        modal:false,
        show:"slide",
        resizable: false,
        width:550,
        close:function() {
            $("#commentForm")[0].reset();//重设表单<{$lang.data}>
            $('#commentTips').removeClass('ui-state-highlight').hide();
        }
    });
});

//<{$lang.operation}><{$lang.tip}>
function alertTip(tip) {
    $('<div title="<{$lang.tip}>"><p align="center">' + tip + '</p></div>').dialog({
        modal: true,
        buttons: {
            '<{$lang.ok}>': function() {
                $(this).dialog("close");
            }
        }
    });
}
//<{$lang.order}><{$lang.detail}>
function detail(orders_code) {
    var url = '/order/order/detail/orders_code/' + orders_code;
    window.open(url);
}
//浏览风格
function swichBrowseType(vSelf) {
    if (browseType == 'fold') {
        browseType = 'unfold';
        $(vSelf).val('<{$lang.shousuo}><{$lang.product}>');
    } else {
        browseType = 'fold';
        $(vSelf).val('<{$lang.zhankai}><{$lang.product}>');
    }
    initData(paginationCurrentPage - 1, paginationPageSize);
}
//<{$lang.product}><{$lang.detail}>

function proDetails(id) {
    if (isNaN(id) || !id) {
        return false;
    }
    var url = '/order/order/prodetail/id/' + id;
    window.parent.$('<iframe id="ifr_order_product_detail" name="ifr_order_product_detail" src="' + url + '" />').dialog({
        title: '<{$lang.order}><{$lang.product}><{$lang.detail}>',
        autoOpen: true,
        width: 900,
        modal: false,
        resizable: false,
        position:'top',
        autoResize: true,
        close:function() {
            $(this).remove();
            if (isReload) {
                window.location.reload();
                isReload = false;
            }
        },
        buttons: {
            '<{$lang.close}>': function() {
                $(this).remove();
            }
        }
    }).width(875);
}

//<{$lang.add}><{$lang.order}>
function addOrder() {
    changeStep('base');
    $('#orderForm')[0].reset();
    $('.orderError').text('').hide();
    $("#order_form").dialog('open');
}
//<{$lang.add}><{$lang.order}>
function submitOrder() {
    jQuery.post('/order/order/create', $('#orderForm').serialize(), submitOrderBack, 'json');
}
function submitOrderBack(data) {
    if (data == null) return;
    if (data.ask == '0') {
        $('.orderError', '#order_form').html('<p>' + data.msg.toString() + '</p>').show();
    } else {
        $("#order_form").dialog('close');
        $('<div title="<{$lang.tip}>"><p><{$lang.congratulation}>，<{$lang.add}><{$lang.order}><{$lang.success}></p></div>').dialog({
            modal: true,
            buttons: {
                '<{$lang.ok}>': function() {
                    $(this).dialog("close");
                    window.open('/order/order/detail/orders_code/' + data.orders_code, '', '');
                }
            }
        });
    }
}

//检查<{$lang.customer_code}>
function checkCustomer(Cid) {
    if(Cid==''){return;}
    $.ajax({
        type: "post",
        async: false,
        dataType: "json",
        url: "/customer/customer/check",
        data:{
            'customer_name':Cid
        },
        success: function(json) {
            if (json.ask == '0') {
                $('.orderError', '#order_form').html('<p><{$lang.customer_has_no_warehouse}></p>').show();
            }
        }
    });
}

function changeStep(id) {
    var msg = '';
    if (id == 'customer') {
        var customer_id = $('#customer_id').val();
        if (customer_id == '') {
            msg = '<{$lang.input}><{$lang.customer_code}>';
        } else {
            checkCustomer(customer_id);
        }
    } else if (id == 'addProduct') {
        var pattern = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/;
        /*if($('#order_user_email').val()=='' ||  pattern.test($('#order_user_email').val())==false){
         msg = '<{$lang.pls_input}><{$lang.email}><{$lang.or}><{$lang.wrong}>';
         }else if($('select#shipping_method').val()==''){
         msg = '<{$lang.pls}><{$lang.shipping_method}>';
         }
         */
        /*
         var len = $(':hidden[name="p_ids[]"]').length;
         if(len==0 || len=='' || len==undefined){
         msg = '<{$lang.pls}><{$lang.product}>...';
         }
         */
    }
    if (msg != '') {
        $('.orderError', '#order_form').html('<p>' + msg + '</p>').show();
    } else {
        $("#base").hide();
        $("#addProduct").hide();
        $("#customer").hide();
        $("#" + id).show();
        $('.orderError', '#order_form').html('').hide();
    }
}

function del(order_id,ws_code,process_status){
	Uorder_code = ws_code;
	var text = process_status==1?("<{$lang.operation}><{$lang.order_back_to_delete}>:"+ws_code):("<{$lang.order_back_to_pickup}>"+ws_code);
	$("#right_confirm p").html(text+',<{$lang.ok}><{$lang.operation}>？ ');
	$("#right_confirm").dialog('open');
}
//问题件
function problem(orders_code) {
    $('#tip_orders_code').text(orders_code);
    $('#comment-dialog').dialog('option', 'buttons', {
        '<{$lang.ok}>': function() {
            var oDialog = $(this);
            var vForm = 'orders_code=' + orders_code + '&' + $('#commentForm').serialize();
            $.post("/order/order/problem", vForm, function(data) {
                if (data == null) return;
                else if (data.ask == 1) {
                    //initData(0);
                    oDialog.dialog('close');
                    alertTip(data.msg);
                } else {
                    $('#commentTips').text(data.msg).show();
                }
            }, 'json');
        },
        '<{$lang.cancel}>': function() {
            $("#commentForm")[0].reset();
            $(this).dialog('close');
        }
    }).dialog("open");
}